package com.paper.tiger.easy.rpc.center;

import com.paper.tiger.easy.rpc.center.config.NettyConfig;
import com.paper.tiger.easy.rpc.center.handler.HeartBeatHanler;
import com.paper.tiger.easy.rpc.center.handler.ServerHanler;
import com.paper.tiger.easy.rpc.core.ExceptionHandler;
import com.paper.tiger.easy.rpc.core.codec.KryoDecoder;
import com.paper.tiger.easy.rpc.core.codec.KryoEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 注册中心netty服务端
 */
public class NettyServer {

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    public void start(NettyConfig config) {

        EventLoopGroup boss = new NioEventLoopGroup(config.getBossThreadNum());
        EventLoopGroup worker = new NioEventLoopGroup(config.getWorkerThreadNum());

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(boss, worker)
                    .localAddress(config.getRegistyPort())
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            ChannelPipeline pp = ch.pipeline();
                            // 发送的数据添加2为数据头
                            pp.addLast(new LengthFieldPrepender(2));
                            // 去除头部
                            pp.addLast(new LengthFieldBasedFrameDecoder(0xFFFF,0,2,0,2));

                            // 解码器 编码器
                            pp.addLast(new KryoDecoder());
                            pp.addLast(new KryoEncoder());

                            pp.addLast(new IdleStateHandler(config.getIdeReadTimeOut(),0,0, TimeUnit.SECONDS));

                            pp.addLast(new HeartBeatHanler());
                            pp.addLast(new ServerHanler());

                            pp.addLast(new ExceptionHandler());

                        }
                    });

            ChannelFuture future = bootstrap.bind().sync();
            log.info("注册中心启动成功 - 监听端口为:{}",config.getRegistyPort());
            // 阻塞主线程,不让服务关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();

        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }


    }
}
